﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Text;
namespace Common.IO
{
    /// <summary>
    /// 缩略图
    /// </summary>
    public static class Thumbnail
    {
        /// <summary>
        /// 创建缩略图(只能指定长或者宽里面的一种，两者都指定的话会失真)
        /// </summary>
        /// <param name="pathImageFrom"></param>
        /// <param name="pathImageTo"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void GenThumbnail(string pathImageFrom, string pathImageTo, int width, int height)
        {
            Image imageFrom = null;
            try
            {
                imageFrom = Image.FromFile(pathImageFrom);
            }
            catch
            {
                //throw;
            }
            if (imageFrom == null)
            {
                return;
            }
            // 源图宽度及高度
            int imageFromWidth = imageFrom.Width;
            int imageFromHeight = imageFrom.Height;


            if (height == 0)
            {
                height = width * imageFromHeight / imageFromWidth;
            }
            else
            {
                width = height * imageFromWidth / imageFromHeight;
            }


            // 生成的缩略图实际宽度及高度
            int bitmapWidth = width;
            int bitmapHeight = height;
            // 生成的缩略图在上述"画布"上的位置
            int X = 0;
            int Y = 0;
            // 根据源图及欲生成的缩略图尺寸,计算缩略图的实际尺寸及其在"画布"上的位置
            if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
            {
                bitmapHeight = imageFromHeight * width / imageFromWidth;
                Y = (height - bitmapHeight) / 2;
            }
            else
            {
                bitmapWidth = imageFromWidth * height / imageFromHeight;
                X = (width - bitmapWidth) / 2;
            }
            // 创建画布
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            // 用白色清空
            g.Clear(Color.White);
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // 指定高质量、低速度呈现。
            g.SmoothingMode = SmoothingMode.HighQuality;
            // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。
            g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
            try
            {
                //经测试 .jpg 格式缩略图大小与质量等最优
                bmp.Save(pathImageTo, ImageFormat.Jpeg);
            }
            catch
            {
            }
            finally
            {
                //显示释放资源
                imageFrom.Dispose();
                bmp.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="FileName">源文件路径</param>
        /// <param name="wText">水印文字</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="font">字体样式</param>
        public static void FinePic(string FileName, string wText, string savePath, Font font)
        {
            Bitmap bmp = new Bitmap(FileName);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.DrawString(wText, font, new SolidBrush(Color.FromArgb(70, Color.Red)), 60, bmp.Height - 120);//加水印
            bmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }


        /// <summary>
        /// 物理存储图片(服务器跟目录下)
        /// </summary>
        /// <param name="postedFile">上传的文件</param>
        /// <returns></returns>
        public static string SavePhoto(HttpPostedFile postedFile)
        {
            string BaseURL = "Uploads";
            DateTime now = DateTime.Now;
            StringBuilder sbF = new StringBuilder("");
            sbF.Append(now.Millisecond.ToString());
            Random rand = new Random();
            sbF.Append(rand.Next(10000, 99999).ToString());
            sbF.Append(rand.Next(10000, 99999).ToString());
            sbF.Append(postedFile.ContentLength.ToString());
            string[] strfile = postedFile.FileName.Split('.');
            string suffixFilename = strfile[strfile.Length - 1];
            sbF.Append(".");
            if (suffixFilename.ToString().ToLower().Equals("jpg") || suffixFilename.ToString().ToLower().Equals("png") || suffixFilename.ToString().ToLower().Equals("gif"))
            {
                sbF.Append(suffixFilename);
                string fileName = sbF.ToString();
                string strBaseLocation = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
                string asd = BaseURL + "\\";
                DateTime d = DateTime.Now;
                asd = asd + d.Year + "\\" + d.Month + "\\" + d.Day + "\\";

                strBaseLocation = strBaseLocation + asd;
                FileDirectoryUtility.CreateDirectory(strBaseLocation);
                string strBaseLocationWeb = "/" + asd.Replace("\\", "/");
                StringBuilder sbL = new StringBuilder(strBaseLocation);
                sbL.Append(fileName);
                StringBuilder sbLWeb = new StringBuilder(strBaseLocationWeb);
                sbLWeb.Append(fileName);
                string OriginphotoURL = sbL.ToString();
                postedFile.SaveAs(OriginphotoURL);
                ChangeImg(OriginphotoURL);
                return sbLWeb.ToString().Replace(".", "_nail.");
            }
            else
            {
                return "";//这里应该放一个默认的错误图片
            }
        }

        private static string ChangeImg(string filepath)
        {
            string fse = filepath.Replace(".", "_nail.");
            Image img = Image.FromFile(filepath);
            if (img.Width > 800)
            {
                Thumbnail.GenThumbnail(filepath, fse, 800, 0);
            }
            else
            {
                Thumbnail.GenThumbnail(filepath, fse, img.Width, 0);
            }
            return fse;
        }
    }
}
